import {
  asyncRouterMap,
} from '@/config/router.config'
import {
  getAll,
  sysGetBaseUserIdRole,
  sysGetBaseRole
} from '@/api/manage/base'
import {
  getSysUserTypeCodeAllRole
} from '@/api/manage/role'
import {
  sysEnterpriseIdAdminList,
  sysAllEnabledEnterprise,
  sysGetEnterpriseIdRelationParkList,
  getEnterpriseIdRelationParkList,
  sysAllEnabledEnterpriseFee,
  getEnterpriseOrParkEnabled,
} from '@/api/manage/enterprise'
import {
  getSysAllParkEnable,
} from '@/api/manage/park'
import { 
    getSysParkIdRange
} from '@/api/manage/parkRange'
import {
  sysGetOperateEnableToIsDelUser
} from '@/api/manage/user'
import {
  BasicLayout
} from '@/layouts'
import { 
    sysUserTypeList, 
} from '@/api/manage/userType'
 import { 
    getSysTaskConfigEnableList
} from '@/api/manage/taskConfig'
import {
  allGetTasksttleUserTemp
} from '@/api/manage/sttle'
import {
  allGetOfflineTaskTemp,
  allGetOfflineTaskSttleTemp
} from '@/api/manage/task'


/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
/* function hasPermission (permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i])
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}


function filterAsyncRouter (routerMap, roles) {
  const accessedRouters = routerMap.filter(route => {
    if (hasPermission(roles.permissionList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
} */

function hasPermission(roles, route) {
  if (roles && roles.length !==0) {
    return roles.some(role => role.code.includes(route.name))
  } else {
    return true
  }
}
export function filterAsyncRoutes(routes, roles, flag) {
  const res = []
  routes = flag ? routes[0].children : routes;
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
       
        tmp.children = filterAsyncRoutes(tmp.children, roles,false)
      }
      res.push(tmp)
    }
  })
  return res
}

let homeRouter = [
  {
    path: '/',
    name: 'index',
    component: BasicLayout,
    meta: { title: '首页' },
    redirect: '/workplace',
    children: []
  }
]

const permission = {
  state: {
    routers: [],
    addRouters: [],
    btns:[],
    sign: false,
    name: '',
    welcome: '',
    avatar: '',
    info: {},
    taskField:[]
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
    },
    SET_IS_ROUTERS: (state,historyRouter) => {
      state.routers = historyRouter
    },
     SET_BTN: (state, btns) => {
      state.btns = btns
    },
    SET_SIGN: (state, sign) => {
      state.sign = sign
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_TASK_CONFIG:(state, arr) => {
      state.taskField = arr
    },
    SET_USER_DETAIL: (state, row) => {
      state.userDetail = row
    }
  },
  actions: {
    generateRoutes ({ commit }) {
      return new Promise((resolve, reject) => {
        getAll().then(response => { 
          const res = response.data;
          const avatar = '/avatar2.jpg';
          commit('SET_SIGN', true);
          commit('SET_INFO', res)
          commit('SET_AVATAR', avatar)
          const menus = res.menus;
          if (menus && menus.length === 0) {
            const accessedRouters = [{
              path: '*', redirect: '/404', hidden: true
            }];
            commit('SET_ROUTERS', accessedRouters)
            resolve(accessedRouters)
          } else if (menus && menus.length >= 1) {
            
            let _menus = [];
            let _butts = [];
            menus.forEach(v=>{
              let params = {};
              params.code = v.menuPath;
              params.name = v.menuName;
              _menus.push(params);
              if(v.children && v.children.length !== 0){
                v.children.forEach(el=>{
                  let child = {};
                  child.code = el.menuPath;
                  child.name = el.menuName;
                  _menus.push(child);
                  if (el.children && el.children.length !== 0) {
                    el.children.forEach(ele => { 
                      _butts.push(ele.menuPath);
                    })
                  }
                })
              }
            })
            let newRouter = filterAsyncRoutes(asyncRouterMap, _menus, true);
            // newRouter.unshift({
            //   path: '/workplace',
            //   name: 'workplaceCode',
            //   component: () => import('@/views/Home'),
            //   meta: { title: '数据分析', keepAlive: true, icon: 'home' }
            // })
            homeRouter[0].children = newRouter
            commit('SET_ROUTERS', homeRouter);
            commit('SET_IS_ROUTERS', menus);
            commit('SET_BTN', _butts);
            resolve(homeRouter)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    ResetRoutes({ commit }, data) {
      commit('SET_SIGN', data)
    },
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_ROUTERS', [])
        resolve()
      })
    },
    sysGetUserTypeData({ commit }) {
      return new Promise((resolve, reject) => {
        sysUserTypeList().then(res => {
          if (res.code === '1') {
             res.data && res.data.forEach(v=>{
              v.value = v.code;
              v.label = v.name;
            })
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    getSysGetBaseUserIdRole({ commit },userId) {
      return new Promise((resolve, reject) => {
        sysGetBaseUserIdRole(userId).then(res => {
          if (res.code === '1') {
             res.data && res.data.forEach(v=>{
              v.value = v.code;
              v.label = v.name;
            })
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    getSysGetBaseUserRole({ commit },roleRelationId) {
      return new Promise((resolve, reject) => {
        sysGetBaseRole(roleRelationId).then(res => {
          if (res.code === '1') {
             res.data && res.data.forEach(v=>{
              v.value = v.roleId;
              v.label = v.roleName;
            })
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    getSysUserTypeCodeAllRole({ commit },roleTypeCode) {
      return new Promise((resolve, reject) => {
        getSysUserTypeCodeAllRole(roleTypeCode).then(res => {
          if (res.code === '1') {
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    sysEnterpriseIdAdminList({ commit },relationId) {
      return new Promise((resolve, reject) => {
        sysEnterpriseIdAdminList(relationId).then(res => {
          if (res.code === '1') {
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    sysAllEnabledEnterprise({ commit },relationId) {
      return new Promise((resolve, reject) => {
        sysAllEnabledEnterprise(relationId).then(res => {
          if (res.code === '1') {
             res.data && res.data.forEach(v => {
              v.value = v.enterpriseId;
              v.label = v.name;
            })
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    sysAllEnabledEnterpriseFee({ commit }) {
      return new Promise((resolve, reject) => {
        sysAllEnabledEnterpriseFee().then(res => {
          if (res.code === '1') {
             res.data && res.data.forEach(v => {
              v.value = v.enterpriseId;
              v.label = v.name;
            })
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    sysGetOperateEnableToIsDelUser({ commit }) {
      return new Promise((resolve, reject) => {
        sysGetOperateEnableToIsDelUser().then(res => {
          if (res.code === '1') {
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    getSysAllParkEnable({ commit }) {
      return new Promise((resolve, reject) => {
        getSysAllParkEnable().then(res => {
          if (res.code === '1') {
            res.data && res.data.forEach(v=>{
              v.value = v.parkId;
              v.label = v.name;
            })
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    getSysParkIdRange({ commit },parkId) {
      return new Promise((resolve, reject) => {
        getSysParkIdRange(parkId).then(res => {
          if (res.code === '1') {
            res.data && res.data.forEach(v=>{
              v.value = v.id;
              v.label = v.itemName;
            })
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    sysGetEnterpriseIdRelationParkList({ commit },enterpriseId) {
      return new Promise((resolve, reject) => {
        sysGetEnterpriseIdRelationParkList(enterpriseId).then(res => {
          if (res.code === '1') {
            resolve(res);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    getEnterpriseIdRelationParkList({ commit },params) {
      return new Promise((resolve, reject) => {
        getEnterpriseIdRelationParkList(params).then(res => {
          if (res.code === '1') {
            resolve(res.data);
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    getSysTaskConfigEnableList({ commit }) {
      return new Promise((resolve, reject) => {
        getSysTaskConfigEnableList().then(res => {
          if (res && res.code === '1') {
            commit('SET_TASK_CONFIG', res.data);
            resolve();
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    allGetTasksttleUserTemp({ commit }) {
      return new Promise((resolve, reject) => {
        allGetTasksttleUserTemp().then(response => {
          let link = document.createElement('a');
          var blob = new Blob([response],{ type: 'application/vnd.ms-excel'});
          link.download = "三要素人员模板.xls";
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },
    allGetOfflineTaskTemp({ commit }) {
      return new Promise((resolve, reject) => {
        allGetOfflineTaskTemp().then(response => {
          var data = response.data;
          let link = document.createElement('a');
          link.href = data;
          link.download = "线下任务模板.xlsx";
          link.style.display = 'none'
          link.click()
          document.body.removeChild(link)
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    },
    allGetOfflineTaskSttleTemp({ commit }) {
      return new Promise((resolve, reject) => {
        allGetOfflineTaskSttleTemp().then(response => {
          var data = response.data;
          let link = document.createElement('a');
          link.href = data;
          link.download = "线下结算模板.xlsx";
          link.style.display = 'none'
          link.click()
          document.body.removeChild(link)
          resolve();
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default permission
